{% load static %}
<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>智能家居系统登录</title>
  <style>
    body {
      font-family: 'Segoe UI', sans-serif;
      margin: 0;
      padding: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      min-height: 100vh;
      /* 渐变背景作为备用 */
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      /* 背景图片设置 */
      background-image: url('{% static "images/background.jpg" %}');
      background-size: cover;
      background-position: center;
      background-repeat: no-repeat;
      background-attachment: fixed;
      position: relative;
    }

    /* 半透明遮罩层，提高文字可读性 */
    body::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.4);
      z-index: 0;
    }

    .container {
      background: rgba(255, 255, 255, 0.9);
      padding: 30px;
      border-radius: 10px;
      width: 350px;
      box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
      position: relative;
      z-index: 1;
      backdrop-filter: blur(5px);
      border: 1px solid rgba(255, 255, 255, 0.2);
    }

    h2 {
      text-align: center;
      color: #333;
    }

    /* 响应式调整 */
    @media (max-width: 480px) {
      .container {
        width: 90%;
        padding: 20px;
      }
    }

    /* 保持原有表单样式不变 */
    .form-group {
      margin: 15px 0;
    }
    .form-group label {
      display: block;
      margin-bottom: 5px;
      color: #555;
    }
    input[type="text"],
    input[type="password"],
    input[type="email"],
    input[type="tel"] {
      width: 100%;
      padding: 8px;
      border: 1px solid #ccc;
      border-radius: 6px;
      box-sizing: border-box;
    }
    .form-group button {
      width: 100%;
      padding: 10px;
      background: #4CAF50;
      border: none;
      color: white;
      font-size: 16px;
      border-radius: 6px;
      cursor: pointer;
    }
    .form-group button:disabled {
      background: #aaa;
      cursor: not-allowed;
    }
    .form-group button:hover:not(:disabled) {
      background: #45a049;
    }
    .switch-link {
      text-align: center;
      margin-top: 10px;
      color: #007BFF;
      cursor: pointer;
      font-size: 14px;
    }
    .switch-link:hover {
      text-decoration: underline;
    }
    .hidden {
      display: none;
    }
  </style>
</head>
<body>
  <div class="container">
    <!-- 登录表单 -->
    <div id="login-form">
      <h2>登录</h2>
      <div class="form-group">
        <label for="login-username">用户名</label>
        <input type="text" id="login-username" placeholder="输入用户名">
      </div>
      <div class="form-group">
        <label for="login-password">密码</label>
        <input type="password" id="login-password" placeholder="输入密码">
      </div>
      <div class="form-group">
        <button id="login-btn">登录</button>
      </div>
      <div class="switch-link" data-target="register">没有账号？注册</div>
      <div class="switch-link" data-target="forgot">忘记密码，创建新密码</div>
    </div>

    <!-- 注册表单 -->
    <div id="register-form" class="hidden">
      <h2>注册</h2>
      <div class="form-group">
        <label for="reg-username">用户名</label>
        <input type="text" id="reg-username" placeholder="输入用户名">
      </div>
      <div class="form-group">
        <label for="reg-email">邮箱</label>
        <input type="email" id="reg-email" placeholder="输入邮箱">
      </div>
      <div class="form-group">
        <label for="reg-phone">手机号</label>
        <input type="tel" id="reg-phone" placeholder="输入手机号">
      </div>
      <div class="form-group">
        <label for="reg-password">密码</label>
        <input type="password" id="reg-password" placeholder="设置密码">
      </div>
      <div class="form-group">
        <button id="register-btn">注册</button>
      </div>
      <div class="switch-link" data-target="login">已有账号？登录</div>
    </div>

    <!-- 忘记密码/新密码表单 -->
    <div id="forgot-form" class="hidden">
      <h2>忘记密码，创建新密码</h2>
      <div class="form-group">
        <label for="forgot-username">用户名</label>
        <input type="text" id="forgot-username" placeholder="请输入用户名">
      </div>
      <div class="form-group">
        <button id="forgot-btn" disabled>创建新密码</button>
      </div>
      <div class="switch-link" data-target="login">返回登录</div>
    </div>
  </div>

  <script>
    // 保持原有JavaScript代码不变
    document.addEventListener('DOMContentLoaded', () => {
      document.getElementById('login-btn').addEventListener('click', login);
      document.getElementById('register-btn').addEventListener('click', register);
      document.getElementById('forgot-btn').addEventListener('click', resetPassword);

      document.querySelectorAll('.switch-link').forEach(el => {
        el.addEventListener('click', () => {
          showForm(el.dataset.target);
        });
      });

      // 只有输入用户名才可点击"创建新密码"
      const fu = document.getElementById('forgot-username');
      const fb = document.getElementById('forgot-btn');
      fu.addEventListener('input', () => {
        fb.disabled = fu.value.trim() === '';
      });
    });

    function showForm(form) {
      ['login','register','forgot'].forEach(f => {
        document.getElementById(f + '-form')
                .classList.toggle('hidden', f !== form);
      });
    }

    async function apiFetch(path, options = {}) {
      const res = await fetch(path, {
        ...options,
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          ...(options.headers || {})
        }
      });
      const text = await res.text();
      let data = {};
      try { data = text ? JSON.parse(text) : {}; } catch {}
      if (!res.ok) {
        const msg = data.detail || data.message || res.statusText;
        throw new Error(msg);
      }
      return data;
    }

    async function resetPassword() {
      const username = document.getElementById('forgot-username').value.trim();
      if (!username) return;

      try {
        // 获取所有用户，检查用户名是否存在
        const users = await apiFetch('/users/all/');
        const user = users.find(u => u.username === username);
        if (!user) {
          return alert('账号不存在');
        }

        // 如果存在，弹框输入新密码
        const newPwd = prompt('请输入新密码：');
        if (!newPwd || newPwd.trim() === '') return;

        // 调接口更新密码
        await apiFetch(`/users/${user.user_id}/update/`, {
          method: 'PUT',
          body: JSON.stringify({ password: newPwd.trim() })
        });
        alert('密码已重置，请使用新密码登录');
        showForm('login');
      } catch (e) {
        alert('操作失败：' + e.message);
      }
    }

    async function login() {
      const u = document.getElementById('login-username').value.trim();
      const p = document.getElementById('login-password').value.trim();
      if (!u || !p) return alert('请填写用户名和密码');
      try {
        const res = await apiFetch('/users/login/', {
          method:'POST',
          body: JSON.stringify({ username: u, password: p })
        });
        if (res.message !== '登录成功') throw new Error(res.message);
        localStorage.setItem('currentUser', res.user.username);
        localStorage.setItem('userRole', res.user.role);
        localStorage.setItem('permissionLevel', res.user.permission_level);
        location.href = res.user.role === '管理员' ? '/user_manage/' : '/index/';
      } catch (e) {
        alert('登录失败：' + e.message);
      }
    }

    async function register() {
      const u = document.getElementById('reg-username').value.trim();
      const p = document.getElementById('reg-password').value.trim();
      const e = document.getElementById('reg-email').value.trim();
      const t = document.getElementById('reg-phone').value.trim();
      if (!u || !p) return alert('请填写用户名和密码');
      try {
        await apiFetch('/users/', {
          method:'POST',
          body: JSON.stringify({
            username: u, password: p,
            email: e, phone: t,
            role: '普通用户', permission_level: 1
          })
        });
        alert('注册成功');
        showForm('login');
      } catch (e) {
        alert('注册失败：' + e.message);
      }
    }
  </script>
</body>
</html>